<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/meow.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/meow.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/blue/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"meowxue.gitee.io","root":"/","images":"/images","scheme":"Muse","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="Java反射技术应用广泛，他能够配置：类的全限定名、方法和参数，完成对象的初始化，甚至是反射某些方法。这样就可以大大增强Java的可配置性，Spring IoC的基本原理也是如次，当然Spring IoC的代码要复杂得多。 Java的反射内容繁多，包括对象的构建、反射方法、注解、参数、接口等。本篇主要讲解对像的构建（包括没有参数和有参数的构建方法）和方法的反射调用。在Java中，反射是通过包 ja">
<meta property="og:type" content="article">
<meta property="og:title" content="Java反射技术">
<meta property="og:url" content="https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/Java%E5%8F%8D%E5%B0%84%E6%8A%80%E6%9C%AF/index.html">
<meta property="og:site_name" content="喵小哥儿の博客">
<meta property="og:description" content="Java反射技术应用广泛，他能够配置：类的全限定名、方法和参数，完成对象的初始化，甚至是反射某些方法。这样就可以大大增强Java的可配置性，Spring IoC的基本原理也是如次，当然Spring IoC的代码要复杂得多。 Java的反射内容繁多，包括对象的构建、反射方法、注解、参数、接口等。本篇主要讲解对像的构建（包括没有参数和有参数的构建方法）和方法的反射调用。在Java中，反射是通过包 ja">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2024-03-11T01:37:00.000Z">
<meta property="article:modified_time" content="2024-03-11T03:18:57.369Z">
<meta property="article:author" content="喵小哥儿">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/Java%E5%8F%8D%E5%B0%84%E6%8A%80%E6%9C%AF/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/Java%E5%8F%8D%E5%B0%84%E6%8A%80%E6%9C%AF/","path":"2024/03/11/技能/java/Java反射技术/","title":"Java反射技术"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Java反射技术 | 喵小哥儿の博客</title>
  







<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/theme-next/theme-next-needmoreshare2@1/needsharebutton.min.css"><style>
#needsharebutton-postbottom {
  cursor: pointer;
  height: 26px;
  margin-top: 10px;
  position: relative;
}
#needsharebutton-postbottom .btn {
  border: 1px solid $btn-default-border-color;
  border-radius: 3px;
  display: initial;
  padding: 1px 4px;
}
</style>
  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">喵小哥儿の博客</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-shuoshuo"><a href="/shuoshuo/" rel="section"><i class="fa fa-comment fa-fw"></i>碎念</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-%E9%80%9A%E8%BF%87%E5%8F%8D%E5%B0%84%E6%9E%84%E5%BB%BA%E5%AF%B9%E8%B1%A1"><span class="nav-number">1.</span> <span class="nav-text">1.1 通过反射构建对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-%E5%8F%8D%E5%B0%84%E6%96%B9%E6%B3%95"><span class="nav-number">2.</span> <span class="nav-text">1.2 反射方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3-%E5%AE%9E%E4%BE%8B"><span class="nav-number">3.</span> <span class="nav-text">1.3 实例</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="喵小哥儿"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">喵小哥儿</p>
  <div class="site-description" itemprop="description">慢热，沉默，抽烟，小酌，喜欢独处，半点斯文，半点猥琐。</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">32</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="mailto:meowxue@163.com" title="E-Mail → mailto:meowxue@163.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i></a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/Java%E5%8F%8D%E5%B0%84%E6%8A%80%E6%9C%AF/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="喵小哥儿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="喵小哥儿の博客">
      <meta itemprop="description" content="慢热，沉默，抽烟，小酌，喜欢独处，半点斯文，半点猥琐。">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Java反射技术 | 喵小哥儿の博客">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java反射技术
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2024-03-11 09:37:00" itemprop="dateCreated datePublished" datetime="2024-03-11T09:37:00+08:00">2024-03-11</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%8A%80%E8%83%BD/" itemprop="url" rel="index"><span itemprop="name">技能</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>1.2k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>4 分钟</span>
    </span>
</div>

          
          
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>Java反射技术应用广泛，他能够配置：类的全限定名、方法和参数，完成对象的初始化，甚至是反射某些方法。这样就可以大大增强Java的可配置性，Spring IoC的基本原理也是如次，当然Spring IoC的代码要复杂得多。</p>
<p>Java的反射内容繁多，包括对象的构建、反射方法、注解、参数、接口等。本篇主要讲解对像的构建（包括没有参数和有参数的构建方法）和方法的反射调用。在Java中，反射是通过包 java.lang.reflect.* 来实现的。</p>
<span id="more"></span>

<h2 id="1-1-通过反射构建对象"><a href="#1-1-通过反射构建对象" class="headerlink" title="1.1 通过反射构建对象"></a>1.1 通过反射构建对象</h2><p>在Java中允许通过反射配置信息构建对象，比如ReflectServiceImpl类，如下面代码所示。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.lean.reflect;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ReflectServiceImpl</span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sayHello</span><span class="params">(String name)</span>&#123;</span><br><span class="line">        System.err.println(<span class="string">&quot;Hello &quot;</span> + name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后通过反射的方法来构建它，如下面代码所示。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> ReflectServiceImp <span class="title function_">getInstance</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="type">ReflectServiceImpl</span> <span class="variable">object</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        object = (ReflectServiceImpl) Class.forName(<span class="string">&quot;com.lean.reflect.ReflectServiceImpl&quot;</span>).newInstance();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> object;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里的代码就是生成一个对象，然后将其返回。下面这行代码的目的就是给类加载器注册了一个类ReflectServiceImpl的全限定名，然后通过newInstance 方法初始化了一个类对象，使用反射的方式也十分简单。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">object = (ReflectServiceImpl) Class.forName(<span class="string">&quot;com.lean.reflect.ReflectServiceImpl&quot;</span>).newInstance();</span><br></pre></td></tr></table></figure>

<p>这是一个构建方法，没有任何参数的类的反射生成，所以还剩下一个问题，如果一个类的所有构建方法里都至少存在一个参数，如何用反射构建它。在Java中，只要稍微改变一下就可以了，例如把ReflectServiceImpl 改造成ReflectServiceImpl2，如下面代码所示。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> com.lean.reflect;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ReflectServiceImpl2</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">ReflectServiceImpl2</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sayHello</span><span class="params">()</span> &#123;</span><br><span class="line">        System.err.println(<span class="string">&quot;Hello &quot;</span> + name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里实现了包含一个参数的构建方法，这时将不能用之前的办法将其反射生成对象，用下面的代码可以完成相同的功能。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> ReflectServiceImp <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">ReflectServiceImpl</span> <span class="variable">object</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        object = Class.forName(<span class="string">&quot;import com.lean.reflect.ReflectServiceImpl2&quot;</span>).getConstructor(String.class).newInstance(<span class="string">&quot;张三&quot;</span>);</span><br><span class="line">    &#125;<span class="keyword">catch</span>(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> object;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用如下代码生成反射对象：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">object = Class.forName(<span class="string">&quot;import com.lean.reflect.ReflectServiceImpl2&quot;</span>).getConstructor(String.class).newInstance(<span class="string">&quot;张三&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>先通过forName加载到类的加载器。然后通过getConstructor方法，它的参数可以是多个，这里定义为String.class，意为有且只有一个参数类型为String的构建方法。通过这个方法可以对重名方法进行排除，此时再用newInstance方法生成对象，只是newInstance方法也多了一个参数“张三” 而已。实际就等于object &#x3D; new ReflectServiceImpl(“张三”)，只是这里用反射机制来生成这个对象而已。</p>
<p>反射的优点是只要配置就可以生成对象，可以解除程序的耦合度，比较灵活。反射的缺点是运行比较慢。但是大部份情况下为了灵活度，降低程序的耦合度，我们还是会使用反射的，比如spring IoC容器。</p>
<h2 id="1-2-反射方法"><a href="#1-2-反射方法" class="headerlink" title="1.2 反射方法"></a>1.2 反射方法</h2><p>再使用反射方法前要获取方法对象，得到了方法才能够去反射。已下面为例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> Object <span class="title function_">reflectMethod</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">Object</span> <span class="variable">returnObj</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="type">ReflectServiceImpl</span> <span class="variable">target</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReflectServiceImpl</span>();</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        <span class="type">Method</span> <span class="variable">method</span> <span class="operator">=</span> ReflectServiceImpl.class.getMethod(<span class="string">&quot;sayHello&quot;</span>, String.class);</span><br><span class="line">        returnObj = method.invoke(target, <span class="string">&quot;张三&quot;</span>);</span><br><span class="line">    &#125;<span class="keyword">catch</span>(NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e)&#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>下面这段代码，当有具体的对象target，儿不知道具体是哪个类时，也可以使用target.getClass.getMethod(“sayHello”, String.class); 代替它，其中第一个参数是方法名称，第二个参数是参数类型，是一个列表，多个参数可以继续编写多个类型，这样便能获得反射的方法对象。反射方法是运用returnObj &#x3D; method.invoke(target, “张三”);代码完成的，第一个参数为target，就是确定用哪个对象调用方法，而“张三”是参数，这行就等同于target.sayHello(“张三”);。如果存在多个对象，可以写成Method.invoke(target, obj1, obj2, obj3……)，这些要根据对象的具体方法来确定。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Method</span> <span class="variable">method</span> <span class="operator">=</span> ReflectServiceImpl.class.getMethod(<span class="string">&quot;sayHello&quot;</span>, String.class);</span><br></pre></td></tr></table></figure>

<h2 id="1-3-实例"><a href="#1-3-实例" class="headerlink" title="1.3 实例"></a>1.3 实例</h2><p>通过实例来看看如何反射生成对象和反射调度方法。继续使用ReflectServiceImpl 类，现在看来看看这样的一个调度方法，如下面代码所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> Object <span class="title function_">reflect</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">ReflectServiceImpl</span> <span class="variable">object</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        object = Class.forName(<span class="string">&quot;&quot;</span>)</span><br><span class="line">        object.getClass().getMethod(<span class="string">&quot;sayHello&quot;</span>, String.class);</span><br><span class="line">        method.invoke(object, <span class="string">&quot;张三&quot;</span>);</span><br><span class="line">    &#125;<span class="keyword">catch</span>(InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException) &#123;</span><br><span class="line">        ex.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> object;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样能反射对象和方法，测试结果如下：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">Hello</span> 张三</span><br></pre></td></tr></table></figure>

<p>对象在反射机制下生成后，反射了方法，这样我们完全可以通过配置来完成对象和方法的反射，大大增强了Java的可配置性和可扩展性，其中Spring IoC就是一个典型的样例。</p>

    </div>

    
    
    

    <footer class="post-footer"><div class="post-widgets">
      <div id="needsharebutton-postbottom">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    </div>
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>喵小哥儿
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://meowxue.gitee.io/2024/03/11/%E6%8A%80%E8%83%BD/java/Java%E5%8F%8D%E5%B0%84%E6%8A%80%E6%9C%AF/" title="Java反射技术">https://meowxue.gitee.io/2024/03/11/技能/java/Java反射技术/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2024/03/06/%E8%BD%AF%E4%BB%B6/eclispe%E7%A8%8B%E5%BA%8F%E5%A4%A7%E7%BA%B2%E6%98%BE%E7%A4%BA%E9%94%99%E8%AF%AF/" rel="prev" title="eclispe程序大纲显示错误">
                  <i class="fa fa-angle-left"></i> eclispe程序大纲显示错误
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2024/03/11/%E6%8A%80%E8%83%BD/java/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86/" rel="next" title="Java动态代理">
                  Java动态代理 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">喵小哥儿</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">25k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">1:29</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  <script src="/js/third-party/pace.js"></script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





  <script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-needmoreshare2@1/needsharebutton.min.js"></script>
  <script>
      pbOptions = {};
        pbOptions.iconStyle = "box";
        pbOptions.boxForm = "horizontal";
        pbOptions.position = "bottomCenter";
        pbOptions.networks = "Wechat,QQZone,Weibo,Douban,Twitter,Facebook";
      new needShareButton('#needsharebutton-postbottom', pbOptions);
  </script>
</body>
</html>
